package com.jeremy.myapplication

import android.annotation.SuppressLint
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

/**
 * Auth :jeremy.wang
 * Date :2022/8/17
 * Des :
 **/
class ModeAdapter(val data: List<ModeData>, val callback: (mode: ModeData) -> Unit) :
    RecyclerView.Adapter<ModeAdapter.ModeViewHolder>() {

    var mSelectedPosition = 0
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ModeViewHolder {
        val view: View = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_mode, parent, false)
        return ModeViewHolder(view)
    }

    override fun onBindViewHolder(holder: ModeViewHolder, position: Int) {
        holder.bind(data[position], position == mSelectedPosition, callback)
    }

    override fun getItemCount() = data.size

    inner class ModeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val btnMode = itemView.findViewById<Button>(R.id.btn_mode)

        @SuppressLint("NotifyDataSetChanged")
        fun bind(data: ModeData, selected: Boolean, callback: (mode: ModeData) -> Unit) {
            btnMode.text = data.title
            if (selected) {
                btnMode.setBackgroundColor(Color.RED)
            } else {
                btnMode.setBackgroundColor(Color.BLUE)
            }
            btnMode.setOnClickListener {
                callback.invoke(data)
                mSelectedPosition = layoutPosition
                notifyDataSetChanged()
            }
        }
    }
}